# -*- encoding:utf-8 -*-

import sys
import os
import re
import urllib
import urllib2
import cookielib
import config

class zhihuSpider:

    def __init__(self):
        self.username, self.password = config.PHONE_NUM, config.PASSWORD_ZHIHU
        self.cookie = cookielib.LWPCookieJar()
        self.cookie.load(config.cookieFile_Zhihu, ignore_discard=True, ignore_expires=True)
        self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie))
        urllib2.install_opener(self.opener)

    def login(self):
        url = urllib2.urlopen('http://www.zhihu.com/#signin').geturl()
        print url

        data = {
            'phone_num': self.username,
            'password': self.password,
            'captcha': ''
        }
        isLogin = False
        failCodePattern = re.compile('&failCode=(\d+)')

        print 'Login...'
        while not isLogin:
            validation = self.opener.open(config.ICODEURL_ZHIHU).read()
            with open('captcha.jpg', 'wb') as file:
                file.write(validation)
            captcha = raw_input('please input validation code：')

            print captcha
            data['captcha'] = captcha
            print data

            request = urllib2.Request(config.LOGINURL_ZHIHU, urllib.urlencode(data))
            response = self.opener.open(request, timeout=20)

            url = response.geturl()
            print url
            failCode = failCodePattern.search(url)
            print "failCode:" + str(failCode)

            print(self.cookie)
            for item in self.cookie:
                if item.name == 'q_c1':
                    # self.userID = item.value
                    self.userID = item.value.split("|")[2]
                    print 'Login Successfully'
                    print(self.userID)
                    self.cookie.save(config.cookieFile,ignore_discard=True, ignore_expires=True)
                    isLogin = True
                    break
        return True

    def getRawContent(self, url, data=None):
        try:
            page = self.opener.open(url, data, timeout=20)
        except Exception, e:
            print 'Fail to login:', e.message
            return
        return page

    def getContent(self, url, data=None):
        return self.getRawContent(url, data).read()

    def getUserID(self):
        return self.userID


if __name__ == '__main__':
    lonelyMan = zhihuSpider()
    lonelyMan.login()
